package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.exam.ExPaper;
import com.qili.entity.it.Tree;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.sys.SysLog;
import com.qili.entity.sys.SysRole;
import com.qili.entity.sys.SysUser;
import com.qili.exception.MyException;
import com.qili.mapper.it.ItDicMapper;
import com.qili.mapper.supervisor.SupervisorFileMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.SysUserService;
import com.qili.service.it.FormBaseService;
import com.qili.service.it.ItDicService;
import com.qili.service.it.ItFileService;
import com.qili.service.it.ItIndexService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.supervisor.SupervisorProjectService;
import com.qili.service.sys.RoleService;
import com.qili.util.*;
import lombok.extern.java.Log;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @date 2021/3/15
 * @Version
 * @description 目录内容详情页
 */
@Log
@Controller
@RequestMapping("/it")
public class DicDetailController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SupervisorFileService fileService;
    @Autowired
    SupervisorFileMapper fileMapper;
    @Autowired
    ItIndexService itIndexService;
    @Autowired
    ItDicService dicService;
    @Autowired
    ItDicMapper itDicMapper;
    @Autowired
    RoleService roleService;
    @Autowired
    private SysUserService userService;
    @Autowired
    ItFileController itFileController;
    @Autowired
    ItFileService itFileService;
    @Autowired
    FormController formController;
    @Autowired
    SupervisorProjectService supervisorProjectService;
    @Autowired
    SupervisorFileService supervisorFileService;


    @Autowired
    @Qualifier("FormBaseService")
    FormBaseService formBaseService;

    @Value("${supervisor.tempPath}")
    private String tempPath;

    @Autowired
    SysLogMapper sysLogMapper;

    /**
     * 点击文件夹显示文件夹内容页面
     *
     * @param dicId
     * @param model
     * @return
     */
    @RequestMapping("/dic/{dicId}")
    public String index(@PathVariable("dicId") String dicId, Model model) {
        log.info("点击了目录,目录id:" + dicId);
        model.addAttribute("dicId", dicId);
        SupervisorFile dic = dicService.selectByPrimaryKey(dicId);
        model.addAttribute("thisDic", dic);
        //判断是否为项目文件并且是否有权限
        String qx = itFileController.downloadQx(dicId);
        List<BaseDict> formFileDictList = DictUtil.getDictByType(DictTypes.FORMFILE);
        //判断该文件夹是不是form文件夹或者是form文件夹的子文件夹:
        String fileFormAbout = getFileFormAbout(dicId);
        if ("2".equals(fileFormAbout)) {
            String formCenterFileId = formBaseService.getFormCenterFileId(dicId);
            if (StringUtils.isNotBlank(formCenterFileId)) {
                model.addAttribute("formCenterFileId", formCenterFileId);
            } else {
                log.warning("表单下的文件夹(" + dicId + "),未找到其表单核心文件夹!");
            }
        }
        model.addAttribute("qx", qx);
        //判断文件是否是项目相关文件:
        String fileAboutProject = "1";
        boolean canDownloadAboutProject = false;
        if ("2".equals(fileAboutProject)) {
            //该文件夹是项目文件的子文件
            //如果是,判断该登录人员是否有下载权限:
            canDownloadAboutProject = true;
        }

        model.addAttribute("fileAboutProject", fileAboutProject);
        model.addAttribute("projectDicCanDown", canDownloadAboutProject ? "1" : "0");
        model.addAttribute("fileIsForm", fileFormAbout);
        if ("1".equals(fileFormAbout)) {
            List<BaseDict> boys = formFileDictList.stream().filter(s -> s.getBadtCode().equals(dicId)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(boys)) {
                model.addAttribute("formTypeCode", boys.get(0).getBadtGroupid());
            }
        }
        //判断用户是否有权限查看详情
        Boolean hasSeeDetailPermission = userService.isHasPermission("it:details");
        model.addAttribute("details", hasSeeDetailPermission ? "1" : "0");
        //判断用户是否是只是知识库用户:
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        boolean zskuser = subject.hasRole("zskuser");
        boolean zsk = subject.hasRole("zsk");
        boolean gsgc = subject.hasRole("gsgc");
        if (zskuser && !zsk && !gsgc) {
            model.addAttribute("onlyzskuser", "1");
        }
        return "itWarehouseCB";
    }

    /**
     * 判断我是不是项目经理或者监理工程师
     *
     * @param dic
     * @return
     */
    private boolean checkProjectDicCanDownload(SupervisorFile dic) {
        if (dic != null && StringUtils.isNotBlank(dic.getProjectId())) {
            SupervisorProject supervisorProject = supervisorProjectService.selectByPrimaryKey(dic.getProjectId());
            String userId = CommonUtil.getUserId();
            boolean isProjectManagerPerson = StringUtils.isNotBlank(supervisorProject.getProjectManagerPerson())
                    && userId.equals(supervisorProject.getProjectManagerPerson());
            boolean isSecondSupervisorEngineer = StringUtils.isNotBlank(supervisorProject.getSecondSupervisorEngineer())
                    && userId.equals(supervisorProject.getSecondSupervisorEngineer());
            return isProjectManagerPerson || isSecondSupervisorEngineer;
        }
        return false;
    }

    /**
     * 判断一个文件或者文件夹与表单的关系
     *
     * @param fileId
     * @return 如果是顶级表单文件夹返回1  如果是表单子文件夹返回2   如果是表单不相关返回3
     */
    public String getFileFormAbout(String fileId) {
        //判断该文件夹是不是form文件夹或者是form文件夹的子文件夹:
        List<BaseDict> formFileDictList = DictUtil.getDictByType(DictTypes.FORMFILE);
        List<String> formFileIds = formFileDictList.stream().map(BaseDict::getBadtCode).collect(Collectors.toList());
        boolean b1 = formController.ifFileForm(fileId);

        String fileIsForm = "";
        //代表文件夹关于form表单的状态:     1代表当前文件夹就是表单文件夹   2 代表当前文件夹是表单文件夹的子文件夹    3代表当前文件夹不是表单相关
        if (b1) {
            if (formFileIds.contains(fileId)) {
                fileIsForm = "1";
            } else {
                fileIsForm = "2";
                //查找对应的表单核心文件夹:
            }
        } else {
            fileIsForm = "3";
        }
        return fileIsForm;
    }

    /**
     * 判断一个文件或者文件夹与项目的关系
     *
     * @param fileId
     * @return 如果是项目配置的项目相关文件夹, 返回1, 如果是项目相关文件夹的子文件夹, 返回2, 如果不是项目相关文件夹返回3
     */
    public String getFileProjectAbout(String fileId) {
        //判断该文件夹是不是form文件夹或者是form文件夹的子文件夹:
        List<BaseDict> projectFileDictList = DictUtil.getDictByType(DictTypes.XMWJ);
        List<String> projectFileIds = projectFileDictList.stream().map(BaseDict::getBadtCode).collect(Collectors.toList());
        boolean b1 = formController.ifFileFroject(fileId);

        String fileIsProject = "";
        //代表文件夹关于form表单的状态:     1代表当前文件夹就是表单文件夹   2 代表当前文件夹是表单文件夹的子文件夹    3代表当前文件夹不是表单相关
        if (b1) {
            if (projectFileIds.contains(fileId)) {
                fileIsProject = "1";
            } else {
                fileIsProject = "2";
                //查找对应的表单核心文件夹:
            }

        } else {
            fileIsProject = "3";
        }
        return fileIsProject;
    }


    /**
     * 文件夹内容页列表:
     *
     * @param dicId
     * @param model
     * @param page
     * @param limit
     * @return
     */
    @ResponseBody
    @RequestMapping("/dicContent/{dicId}")
    public ReType index(@PathVariable("dicId") String dicId, Model model, Integer page, Integer limit, String fileName) {
        log.info("获取目录id:" + dicId + "下的内容列表");
        //判断用户是否拥有查看所有IT文件夹的角色
        boolean seeAll = itIndexService.canISeeAll();
        List<String> userRoleList = CommonUtil.getUserRoleList();
        Map paraMap = new HashMap();
        paraMap.put("superiorId", dicId);
        if (!seeAll) {
            paraMap.put("examine", userRoleList);
        }
        if (StringUtils.isNotBlank(fileName)) {
            paraMap.put("fileName", "%" + fileName + "%");
        }
        //判断是不是项目文件夹下面:
        //如果是项目相关的文件夹,即使该用户没有查看权限,依然能够看到:
        SupervisorFile thisDic = dicService.selectByPrimaryKey(dicId);
        //判断该文件夹是不是项目相关文件夹：
        String fileProjectAbout = getFileProjectAbout(dicId);
        if ("1".equals(fileProjectAbout) || "2".equals(fileProjectAbout)) {
            //是项目相关文件：
            String examineUser = thisDic.getExamineUser();
            //如果该文件夹不能被系统管理员、知识库管理员、公司高层查看，并且当前登录人员为项目经理或者监理工程师角色：
            //这个时候只能查看项目相关的
            if (!(userRoleList.contains("admin") && examineUser.contains("admin"))
                    && (!userRoleList.contains("zsk") && examineUser.contains("zsk"))
                    && (!userRoleList.contains("gsgc") && examineUser.contains("gsgc"))
                    && (userRoleList.contains("xmjl") || userRoleList.contains("jlgcs"))) {
                paraMap.put("project", "1");
                paraMap.put("userId", CommonUtil.getUserId());
            }
        }
        List<SupervisorFile> fileList = null;
        Page<SupervisorFile> tPage = PageHelper.startPage(page, limit);
        try {
            fileList = itDicMapper.selectDicContent(paraMap);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), fileList);
    }

    /**
     * 显示新建文件夹
     *
     * @param dicId
     * @param model
     * @return
     */
    @GetMapping("/dic/newDic")
    @RequiresPermissions("it:newFolder")
    public String itNewDic(String dicId, Model model) {
        //获取所有的角色：
        List<SysRole> sysRoles = roleService.selectAll();
        model.addAttribute("roleList", sysRoles);
        model.addAttribute("dicId", dicId);
        return "addDic";
    }

    /**
     * @param supervisorFile
     * @return
     * @Desc 判断新文件夹名称是否重复
     */
    @ResponseBody
    @GetMapping("/dic/checkName")
    public JsonUtil checkNewNameExit(SupervisorFile supervisorFile) {
        JsonUtil result = JsonUtil.sucess("成功");
        if (StringUtils.isBlank(supervisorFile.getFileName()) || StringUtils.isBlank(supervisorFile.getSuperiorId())) {
            throw new RuntimeException("判断新文件夹名称是否重复时，新文件夹名称或者所在目录id为空");
        }
        if (dicService.selectCount(supervisorFile) > 0) {
            result.setFlag(false);
            result.setMsg("已经存在的文件夹名称");
        }
        return result;
    }

    /**
     * 新建文件夹
     *
     * @param newDic
     * @return
     */
    @ResponseBody
    @PostMapping("/dic/new")
    public JsonUtil saveNewDic(SupervisorFile newDic) {
        //再次验证是否存在该文件夹
        if (StringUtils.isBlank(newDic.getFileName()) || StringUtils.isBlank(newDic.getSuperiorId())) {
            return JsonUtil.error("新建文件夹，参数异常");
        }
        if (StringUtils.isBlank(newDic.getZskfileType())) {
            newDic.setZskfileType("1");
        }
        int i = dicService.selectCount(newDic);
        if (i > 0) {
            return JsonUtil.error("已经存在的文件夹名称");
        }

        //创建新文件夹：
        //根据所在目录id查询父级目录的真实路径：
        SupervisorFile parentFile = dicService.selectByPrimaryKey(newDic.getSuperiorId());
        if (null == parentFile) {
            return JsonUtil.error("创建新文件夹时，所在目录不存在");
        }
        String parentPath = parentFile.getUrl();
        if (StringUtils.isBlank(parentPath)) {
            return JsonUtil.error("创建新文件夹时，所在目录路径为空");
        }
        File parentOsFile = new File(parentPath);
        if (!parentOsFile.exists()) {
            return JsonUtil.error("创建新文件夹时，所在目录磁盘中不存在");
        }
        String newDicPath = parentPath.endsWith(File.separator) ? parentPath + newDic.getFileName() : parentPath + File.separator + newDic.getFileName();
        //磁盘中的文件
        File newDicFile = new File(newDicPath);
        //数据库中的文件:
        SupervisorFile exitedFile = new SupervisorFile();
        exitedFile.setUrl(newDicPath);
        List<SupervisorFile> select = dicService.select(exitedFile);

        if (newDicFile.exists() && CollectionUtil.isNotEmpty(select)) {
            return JsonUtil.error("已经存在的文件夹");
        } else {
            boolean mkdir = true;
            if (!newDicFile.exists()) {
                mkdir = newDicFile.mkdir();
            }
            if (mkdir && CollectionUtil.isEmpty(select)) {
                newDic.setUrl(newDicFile.getPath());
                dicService.insertSelective(newDic);
                // 2022年5月18日13:38:19 新增 path_key 需要id
                String key = parentFile.getPathKey() + "," + newDic.getId();
                itFileService.updatePathKeyById(newDic.getId(),key);
                JsonUtil result = new JsonUtil();
                result.setMsg("创建成功");
                result.setData(newDic);
                result.setFlag(true);
                return result;
            }
            return JsonUtil.error("创建失败");
        }
    }

    /**
     * 显示上传文件页面
     *
     * @param dicId
     * @return
     */
    @GetMapping("/dic/showUpload")
    @RequiresPermissions("it:uploading")
    public String showUploadPage(String dicId, Model model) {
        model.addAttribute("dicId", dicId);
        return "uploadFile";
    }

    /**
     * 上传文件
     *
     * @param filedata
     * @param file
     * @return
     */
    @RequestMapping(value = "/dic/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil addFile(@RequestParam(value = "file", required = false) MultipartFile filedata, SupervisorFile file) {
        //当前用户信息
        String userId = CommonUtil.getUserId();
        String fileName = filedata.getOriginalFilename();
        if (fileName.indexOf(".") != -1) {
            if (!itFileService.checkCanUpload(fileName)) {
                return JsonUtil.error("不支持的文件类型");
            }
        }
        if (fileName.indexOf(File.separator) != -1) {
            fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
        }
        SysUser sysUser = userService.selectByPrimaryKey(userId);
        if (null == file || StringUtils.isBlank(file.getSuperiorId())) {
            return JsonUtil.error("上传文件时，所在目录id为空");
        }
        //查询目录：
        SupervisorFile dicFile = dicService.selectByPrimaryKey(file.getSuperiorId());
        if (null == dicFile || StringUtils.isBlank(dicFile.getUrl())) {
            return JsonUtil.error("上传文件时，所在目录url为空");
        }

        //保存文件
        try {
            String newFilePath = dicFile.getUrl().endsWith(File.separator) ? dicFile.getUrl() + fileName
                    : dicFile.getUrl() + File.separator + fileName;
            File newFile = new File(newFilePath);
            if (newFile.exists()) {
                return JsonUtil.error("已经存在的文件名称");
            }
            FileUtils.copyInputStreamToFile(filedata.getInputStream(), newFile);
            //保存文件表
            file.setUrl(newFile.getPath());
            file.setZskfileType("2");
            file.setFileName(fileName);
            if (fileName.indexOf(".") != -1) {
                file.setFileType(fileName.substring(fileName.lastIndexOf(".")));
            }
            dicService.insertSelective(file);
            // 2022年5月18日14:03:47 新增 path_key 需要id
            String key = dicFile.getPathKey() + "," + file.getId();
            itFileService.updatePathKeyById(file.getId(),key);
            String  param="参数：文件名称：" + fileName;
            String  text="上传文件";
            String type="ADD";
            insertFileLog(text,param,type);
            // 解析文件
            try {
                supervisorFileService.parseFileToText(file);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return JsonUtil.sucess("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return JsonUtil.error("上传失败");
        }
    }

    //日志
    public void insertFileLog(String text,String param,String type ) {


        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType(type);
        sysLog.setText(text);
        sysLog.setParam(param);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser currentUser = Principal.getCurrentUse();
        sysLog.setUserName(currentUser.getUsername());
        sysLogMapper.insert(sysLog);
    }

    /**
     * 压缩后下载
     *
     * @param dicId
     * @param fileIds
     * @param request
     * @param response
     */
    @RequestMapping(value = "/dic/download")
    public void download(String dicId, String fileIds, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isNotBlank(fileIds)) {
            if (StringUtils.isNotBlank(dicId)) {
                SupervisorFile dic = dicService.selectByPrimaryKey(dicId);
                String dicName = dic.getFileName();
                String AsOutPath = tempPath + File.separator + dicName + DateUtil.getCurrentDateTimeStringNoSpliter() + ".zip";
                try {
                    String[] split = fileIds.split(",");
                    List<String> fileIdList = Arrays.asList(split);
                    List<String> filePathList = new ArrayList<>();
                    String  param="参数：文件名称：";
                    for (String fileId : fileIdList) {
                        if (StringUtils.isNotBlank(fileId)) {
                            SupervisorFile supervisorFile = dicService.selectByPrimaryKey(fileId);
                            if (StringUtils.isNotBlank(supervisorFile.getUrl())) {
                                filePathList.add(supervisorFile.getUrl());
                                //添加下载次数:
                                dicService.addDownloads(fileId);
                            }
                            param=param+supervisorFile.getFileName()+";";
                        }
                    }

                    String  text="批量下载";
                    String type="UPDATE";
                    insertFileLog(text,param,type);
                    ZipUtils.compress(AsOutPath, filePathList);

                } finally {

                }
                ExportFileUtil.exportFile(response, request, AsOutPath);
            }
        }
    }

    /**
     * 判断文件夹是否可以删除
     *
     * @param file 包含文件夹id的对象
     * @return
     */
    @ResponseBody
    @GetMapping("/dic/checkCanDel")
    public JsonUtil checkCanDel(SupervisorFile file) {
        if (null == file || StringUtils.isBlank(file.getId())) {
            return JsonUtil.error("参数错误");
        }

        Example example = new Example(SupervisorFile.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("superiorId", file.getId());
        Example.Criteria criteria2 = example.createCriteria();
        criteria2.andNotEqualTo("deleteState", "2");
        example.and(criteria2);
        int i = dicService.selectCountByExample(example);
        if (i > 0) {
            return JsonUtil.error("有下级文件,不允许删除");
        }
        return JsonUtil.sucess("可以删除");
    }

    /**
     * 删除文件(伪删除)
     *
     * @param fileId
     * @return
     */

    @ResponseBody
    @PostMapping("/dic/del/{fileId}")
    @RequiresPermissions("it:delete")
    public JsonUtil deleteFile(@PathVariable("fileId") String fileId) {
        SupervisorFile delFile = new SupervisorFile();
        delFile.setId(fileId);
        delFile.setDeleteState("2");
        delFile.setDeleteDate(DateUtil.getCurrentDateString());
        delFile.setDeleteUser(CommonUtil.getUserId());
        dicService.updateByPrimaryKeySelective(delFile);
        SupervisorFile supervisorFile = supervisorFileService.selectByPrimaryKey(fileId);
        if(supervisorFile!=null){
            String  param="参数：文件名称：" + supervisorFile.getFileName();
            String  text="删除文件";
            String type="DEL";
            insertFileLog(text,param,type);
        }
        return JsonUtil.sucess("删除成功");
    }

    /**
     * 显示目录树页面
     *
     * @param file
     * @return
     */
    @GetMapping("/dic/showDicTree")
    @RequiresPermissions("it:move")
    public String showDicTree(SupervisorFile file, Model model) {
        model.addAttribute("fileId", file.getId());
        return "move2";
    }

    /**
     * 移动页面 树数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/dic/getAllDic")
    public List<Tree> selectAllDic() {
        return dicService.selectAllDic();
    }

    /**
     * 设置目录属性树数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/dic/getAllDicSeted")
    public List<Tree> getAllDicSeted() {
        return dicService.getAllDicSeted();
    }

    /**
     * 移动文件/文件夹
     *
     * @param sourceFileId
     * @param targetFileId
     * @return
     */
    @ResponseBody
    @PostMapping("/dic/move")
    public JsonUtil moveFile(String sourceFileId, String targetFileId) {
        if (StringUtils.isBlank(sourceFileId) || StringUtils.isBlank(targetFileId)) {
            return JsonUtil.error("参数错误");
        }
        // 当前需要移动的数据
        SupervisorFile sourceFile = dicService.selectByPrimaryKey(sourceFileId);
        if (null == sourceFile || StringUtils.isBlank(sourceFile.getUrl())) {
            return JsonUtil.error("没有找到需要移动的文件");
        }
        // 当前需要移动的目标文件
        SupervisorFile targetDic = dicService.selectByPrimaryKey(targetFileId);
        if (null == targetDic || StringUtils.isBlank(targetDic.getUrl())) {
            return JsonUtil.error("没有找到目标文件夹");
        }
        //移动后的文件路径：
        String newSourceFilePath = targetDic.getUrl().endsWith(File.separator) ? targetDic.getUrl()
                + sourceFile.getFileName() : targetDic.getUrl() + File.separator + sourceFile.getFileName();

        File futureFile = new File(newSourceFilePath);
        if (futureFile.exists()) {
            return JsonUtil.error("移动失败,目标路径包含同名的文件或文件夹");
        }
        File parentFile = futureFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        //移动文件
        File sourceOsFile = new File(sourceFile.getUrl());
        if (sourceOsFile.exists()) {
            if (sourceOsFile.renameTo(futureFile)) {
                //更改资源文件的父级为目标文件夹id
                SupervisorFile newFile = new SupervisorFile();
                newFile.setId(sourceFile.getId());
                newFile.setSuperiorId(targetDic.getId());
                newFile.setUrl(futureFile.getPath());
                // 2022年8月16日14:17:27 更新path_key
                newFile.setPathKey(targetDic.getPathKey() + "," + sourceFile.getId());
                //判断目标文件夹是不是表单:
                String fileFormAbout = getFileFormAbout(targetFileId);
                //如果目标文件夹是表单下级文件夹,并且不是表单核心文件夹(移动到核心文件夹下面,我知道你是表单的哪种文件),并且有type
                if ("2".equals(sourceFile.getZskfileType()) && "2".equals(fileFormAbout)
                        && StringUtils.isBlank(targetDic.getFormCenter())
                        && (StringUtils.isNotBlank(targetDic.getType()) && targetDic.getType().length() == 10)) {
                    //获取目标表单核心文件夹:
                    String formCenterFileId = formBaseService.getFormCenterFileId(targetFileId);
                    newFile.setLinkId(formCenterFileId);
                    newFile.setType(targetDic.getType());
                }
                if ("1".equals(sourceFile.getZskfileType())) {
                    //如果是文件夹移动,继承目标文件夹的权限:
                    newFile.setCanotSeeRoles(targetDic.getCanotSeeRoles());
                    newFile.setExamineUser(targetDic.getExamineUser());
                    newFile.setDownloadUser(targetDic.getDownloadUser());
                }
                dicService.updateByPrimaryKeySelective(newFile);
                //更改文件夹下面的url:
                dicService.formatDicFiles(newFile);
                return JsonUtil.sucess("移动成功");
            } else {
                return JsonUtil.error("移动失败");
            }
        } else {
            return JsonUtil.error("需要移动的文件不存在");
        }
    }

    /**
     * 显示权限设置页面
     *
     * @param file
     * @param model
     * @return
     */
    @GetMapping("/dic/permission/page")
    @RequiresPermissions("it:permission")
    public String showSetDicPermission(SupervisorFile file, Model model) {
        if (null == file || StringUtils.isBlank(file.getId())) {
            throw new RuntimeException("参数错误");
        }
        SupervisorFile dic = dicService.selectByPrimaryKey(file.getId());
        model.addAttribute("dicFile", dic);
        if (StringUtils.isNotBlank(dic.getCreateBy())) {
            SysUser creator = userService.selectByPrimaryKey(dic.getCreateBy());
            model.addAttribute("dicCreator", creator);
        }
        //获取拥有查看权限的角色：
        List<Map> roleList = dicService.selectDicRoleList(file.getId());
        model.addAttribute("dicRoleList", roleList);
        return "setpermission";
    }

    @ResponseBody
    @PostMapping("/dic/updateFile")
    public JsonUtil updateFile(SupervisorFile file) {
        if (null == file || StringUtils.isBlank(file.getId())) {
            return JsonUtil.error("参数错误");
        }
        dicService.updateByPrimaryKeySelective(file);
        if (StringUtils.isNotBlank(file.getFormCode()) && "permission".equals(file.getFormCode())) {
            //更改其下面的目录的权限:
            dicService.updateChildDicPermission(file);
        }
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @PostMapping("/addDownloads")
    public JsonUtil updateDownloadCount(String fileId) {
        dicService.addDownloads(fileId);
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @PostMapping("/addViewCount")
    public JsonUtil updateViewCount(String fileId) {
        dicService.addViewCount(fileId);
        return JsonUtil.sucess("操作成功");
    }

}
